<?php
/**
 * 
 **/
namespace Xijie\Controller;
use Think\Controller;

class WapController extends Controller {
	/**
	 * Index
	 **/
	public function index(){
		if(IS_GET){
			$ajax = I('ajax') ? (int)I('ajax') : 0;
			if($ajax){
				$phone = I('phone') ? trim(I('phone')) : '';
				$code = I('code') ? trim(I('code')) : '';
				$btime = I('btime') ? trim(I('btime')) : '';
				$etime = I('etime') ? trim(I('etime')) : '';
				
				//查询信息
				$info = D('Member')->getMemberInfoByPhone($phone, $code, 0);
				if(is_array($info) && count($info)){
					$this->assign('info', $info);
					$newArray = array();
					//根据合同号获取设备信息--当前费用
					$eqminfo = D('EqmentRoom')->getEqmentInfoByContract($info['contract']);
					if(is_array($eqminfo) && count($eqminfo)){
						foreach($eqminfo as $ls){
							$newArray[$ls['typeid']] = $ls;
						}
					}
					
					$roomnumber = $info['room_number'];
					//查询历史费用 --- 根据时间查询抄表日志表
					if(!empty($btime) && empty($etime)){
						$paylog = D('Paylog')->getPayLogGroupByType(array(
							'contract' => $info['contract'],
							'paytime' => array('gt', strtotime($btime))
						));
						//记录
						//D('Paylog')->getEqmentLogByWhere($where=array(), $order=array());
						$where = array(
							'roomnumber' => $roomnumber,
							'last_time' => array('gt', $btime.' 00:00:00')
						);
					}else if(empty($btime) && !empty($etime)){
						$paylog = D('Paylog')->getPayLogGroupByType(array(
							'contract' => $info['contract'],
							'paytime' => array('lt', strtotime($etime))
						));
						
						$where = array(
							'roomnumber' => $roomnumber,
							'last_time' => array('lt', $etime.' 23:59:59')
						);
					}else if(!empty($btime) && !empty($etime)){
						$paylog = D('Paylog')->getPayLogGroupByType(array(
							'contract' => $info['contract'],
							'paytime' => array('between', array(strtotime($btime), strtotime($etime)))
						));
						
						$where = array(
							'roomnumber' => $roomnumber,
							'last_time' => array('between', array($btime.' 00:00:00', $etime.' 23:59:59'))
						);
					}else{
						$paylog = D('Paylog')->getPayLogGroupByType(array(
							'contract' => $info['contract']
						));
						
						$where = array(
							'roomnumber' => $roomnumber
						);
					}
					
					//获取初始值
					if(is_array($paylog) && count($paylog)){
						foreach($paylog as $ls){
							$where['typeid'] = $ls['type_id'];
							$newArray[$ls['type_id']]['his_point'] = $ls['points'];
							$newArray[$ls['type_id']]['his_frist'] = D('Paylog')->getEqmentLogByWhere($where, 'last_time asc');
							$newArray[$ls['type_id']]['his_last'] = D('Paylog')->getEqmentLogByWhere($where, 'last_time desc');
						}
					}
					
					$this->assign('eqminfo', $newArray);
					//跳转界面
					$html = $this->fetch('ajax_index2');
					//组装数据
					$data = array(
						'errCode' => 1,
						'html' => $html
					);
				}else{
					$data = array('errCode' => 0);
				}
				
				$this->ajaxReturn($data);
			}else{
				$this->display('index2');
			}
		}
	}
	
	//登陆用户
	public function login(){
		if(IS_GET){
			$this->display('WapCost/login');
		}else{
			$phone = I('post.phone', '');
			$code = I('post.code', '');

			if(empty($phone) || empty($code)){
				echo json_encode(array(
					'errCode' => 0,
					'message' => '参数错误'
				));
			}else{
				//根据条件查询会员信息
				$uinfo = D('Member')->getMemberInfoByPhone($phone, $code);
				if(is_array($uinfo) && count($uinfo)){
					echo json_encode(array(
						'errCode' => 1,
						'message' => '成功',
						'roomnumber' => $uinfo['room_number'],
						'member_id' => $uinfo['member_id']
					));
				}else{
					echo json_encode(array(
						'errCode' => 0,
						'message' => '会员不存在'
					));
				}
			}
		}
	}

	/**
	 * 账单查询
	 * 2017-01-15 修改账单查询条件，按合同号查询
	 **/
	public function cost(){
		$roomnumber = I('get.roomnumber', '');
		$memberid = I('get.mid', 0); //用户ID
		if(empty($roomnumber)){
			$this->display('WapCost/login'); //跳转到登陆界面
		}else{
			$month = I('get.month', date('Y-m'));
			$ajax = I('get.ajax', 0);
			//获取月份
			for($i=5;$i>=0;$i--){
				$times = strtotime("-". $i ." month");
				$monthArray[] = array(
					'years' => date('Y', $times),
					'month' => date('m', $times)
				);
			}
			//查询用户信息
			$uinfo = D('Member')->getMemberInfoById($memberid);
			//设置用户信息
			$this->assign('nickname', $uinfo['member_nick']);
			$this->assign('mid', $uinfo['member_id']);
			$this->assign('contract', $uinfo['contract']);
			//获取当月固定账单
			$costlist = D('Costlog')->getCostInfoByWhere(array(
				'month' => $month,
				'roomnumber' => $roomnumber,
				'contract' => $uinfo['contract'],
				'order_type' => 1
			));
			//上月日常账单日期
			$upmonth = date('Y-m', strtotime("-1 month", strtotime($month."-01")));
			//获取上月日常账单
			$costlist2 = D('Costlog')->getCostInfoByWhere(array(
				'month' => $upmonth,
				'roomnumber' => $roomnumber,
				'contract' => $uinfo['contract'],
				'order_type' => 2
			));
			
			$newArray = array(
				1 => array(
					'rent' => 0,
					'property' => 0
				),
				2 => array(
					'rates1' => 0,
					'rates2' => 0
				)
			);

			//支付状态
			$status = 1;
			if(count($costlist)){
				if($costlist['status'] == 1){
					$status = 1;
				}else{
					$status = 0;
				}
				
				if($costlist['account'] == $costlist['rent']){
					$costlist['property'] = 0;
				}else if($costlist['account'] == $costlist['property']){
					$costlist['rent'] = 0;
				}else if($costlist['account'] == 0){
					$costlist['property'] = $costlist['rent'] = 0;
				}
				
				$newArray[$costlist['order_type']] = $costlist;
			}
			
			if(count($costlist2)){
				if($costlist2['status'] == 1){
					$status = 1;
				}else{
					$status = 0;
				}

				$newArray[$costlist2['order_type']] = $costlist2;
			}
			
			$this->assign('status', $status);
			$this->assign('timeArray', $monthArray);
			$this->assign('costlist', $newArray);
			$this->assign('roomnumber', $roomnumber);
			$this->assign('month', $month);
			$this->assign('upmonth', $upmonth);
			if(!$ajax){
				$this->display('WapCost/index');
			}else{
				$this->display('WapCost/lists', 'utf-8', 'html');
			}
		}	
	}

	/**
	 * User Info
	 **/
	public function ajax(){
		$phone = I('get.phone') ? trim(I('get.phone')) : '';
		$code = I('get.code') ? trim(I('get.code')) : '';
		$type = I('get.type') ? (int)I('get.type') : 1;
		
		//用户信息
		$info = D('Member')->getMemberInfoByPhone($phone, $code);
		if(is_array($info) && count($info)){
			if($info['leaving_time'] < time()){
				//判断是否在48小时之内，并且是长租客人 istype == 1
				//echo $this->diffBetweenTwoDays($info['leaving_time'], time());
				if($info['istype'] == 1 && $this->diffBetweenTwoDays($info['leaving_time'], time()) <= 2){
					$msg = "您的卡已失效，请购买临时卡（收取卡押金￥100.00）制卡，有效开门时间24小时。请及时到公寓管家处办理续费和退卡手续。";
					//判断是否存在制卡记录
					$infos = D('Roomcard')->getRoomCardInfoByWhere(array(
						'member_id' => $info['member_id'],
						'is_back' => 0
					));
					//设置参数
					$info['btime'] = $info['begintime'] = date('ymdHi', time());
					//判断时间
					if(is_array($infos) && count($infos)){
						$info['etime'] = date('ymdHi', $infos['leav_time']);
					}else{
						$info['etime'] = date('ymdHi', (time() + 86400));
					}
					//设置锁号
					$info['locknum'] = str_pad($info['room_number'], 6, '01', STR_PAD_LEFT).'99';
					$info['iscq'] = 1;
					
					$this->ajaxReturn(array(
						'errCode' => 1,
						'errMsg' => $msg,
						'info' => $info,
					));
				}else{
					$this->ajaxReturn(array(
						'errCode' => 0,
						'errMsg' => '您的租期已失效'
					));
				}
			}else{
				if($type == 1){
					//设置参数
					if($info['checkin_time'] >= time()){
						$btime = $info['checkin_time'];
					}else{
						$btime = time();
					}
					
					//判断结束时间是否是大于1个月
					$month = $this->getMonthNum(date('Y-m-d', $info['leaving_time']), date('Y-m-d', time()));
					if($month > 1){
						$etime = strtotime("+1 month");
					}else{
						$etime = $info['leaving_time'];
					}
					
					//设置锁号
					$info['locknum'] = str_pad($info['room_number'], 6, '01', STR_PAD_LEFT).'99';
					
					$msg = "尊敬的 ". $info['room_number'] ." 房间 ". $info['member_nick'] ." 客人，您好！<br />
					您的房租有效期是：". date('Y-m-d H:i', $btime)."~". date('Y-m-d H:i', $etime) ."<br />
					";
					//格式化时间
					$info['btime'] = $info['begintime'] = date('ymdHi', $btime);
					$info['etime'] = date('ymdHi', $etime);
					$info['iscq'] = 0;
					$this->ajaxReturn(array(
						'errCode' => 1,
						'errMsg' => $msg,
						'info' => $info,
					));
				}else{
					//
				}
			}
		}else{
			$this->ajaxReturn(array(
				'errCode' => 0,
				'errMsg' => '查询不到您的信息，请与管理员确认！'
			));
		}	
	}
	
	public function pay(){
		if(IS_GET){
			$this->display('WapCost/pay');
		}
	}
	
	//合并账单
	public function costorder(){
		$roomnumber = I('post.roomnumber', 0);
		$month = I('post.month', '');
		$paymethod = I('post.pay', '');
		$contract = I('post.contract', '');
		//参数错误
		if(empty($roomnumber) || empty($month) || empty($paymethod)){
			$array = array('errCode'=> 0, 'errMsg' => '参数错误'. $roomnumber . $month . $paymethod);
		}else{
			//开始生成订单
			$gdorder = D('Costlog')->getCostInfoByWhere(array(
				'roomnumber' => $roomnumber,
				'month' => $month,
				'contract' => $contract,
				'status' => 0,
				'order_type' => 1
			));
			
			$rcorder = D('Costlog')->getCostInfoByWhere(array(
				'roomnumber' => $roomnumber,
				'month' => date('Y-m', strtotime("-1 month", strtotime($month."-01"))),
				'status' => 0,
				'contract' => $contract,
				'order_type' => 2
			));
			
			if(count($gdorder)){
				$list[] = $gdorder;
			}
			
			if(count($rcorder)){
				$list[] = $rcorder;
			}
			
			if(count($list)){
				$costorder_id = ''; //合并订单
				$costorderTotal = 0;
				$contract = '';
				foreach($list as $ls){
					$costorder_id .= strlen($costorder_id) ? ','. $ls['order_id'] : $ls['order_id'];
					$costorderTotal += $ls['account'];
					$contract = $ls['contract'];
				}
				//合并订单
				$ordersn = 'Cost_'. time();
				//判断是否存在相同的订单
				$row = M('order')->data(array(
					'order_sn' => $ordersn,
					'point' => $costorderTotal,
					'desc' => $month. '月账单',
					'createtime' => time(),
					'room_number' => $roomnumber,
					'costorder' => $costorder_id,
					'contract' => $contract
				))->add();
				if($row){
					$array = array('errCode'=> 1, 'errMsg' => '合并账单成功', 'orderid' => $row);
				}
			}else{
				$array = array('errCode'=> 0, 'errMsg' => '暂无有效账单');
			}
		}

		echo json_encode($array);
	}
	
	//微信账单缴费
	public function weixinpay(){
		//获取参数
		$orderid = I('get.oid', 0);
		$roomnumber = I('get.rn', '');
		//判断请求页面类型
		$pageType = I('get.ptye', 'jiaofei');

		if($pageType == 'jiaofei'){
			$orderInfo = M('order')->where(array(
				'id' => $orderid,
				'status' => 0,
				'room_number' => $roomnumber
			))->find();
			$ordersn = $orderInfo['order_sn'];
			$notify_url = "http://mamagy.com/xj/wap/wxnotify.html";
			$desc = $orderInfo['desc'];
		}else if($pageType == 'yuyue'){
			//获取订单详情
			$orderInfo = M('yuyue_order')->where(array(
				'orderid' => $orderid
			))->find();
			$ordersn = $orderInfo['ordersn'];
			$notify_url = "http://mamagy.com/xj/yuyue/wxnotify.html";
			$desc = '租房定金';
		}

		if(count($orderInfo)){
			$costorderTotal = $orderInfo['point'];
			//账单生成成功后调用支付方式
			import("Org.Util.JsApiPay");
			$jsApi = new \JsApiPay();
			$openid = $jsApi->GetOpenid();
			
			//设置支付参数
			$input = new \WxPayUnifiedOrder();
			$input->SetBody("缴费");
			$input->SetOut_trade_no($ordersn);
			$input->SetTotal_fee($costorderTotal * 100);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			$input->SetNotify_url($notify_url); //回调函数
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openid);
			//统一订单
			$order = \WxPayApi::unifiedOrder($input);
			
			//获取JS参数
			$param = $jsApi->GetJsApiParameters($order);
			//getPrepayId
			$this->assign('jsApiParameters', $param);
			$this->assign('desc', $desc);
			$this->assign('total_fee', $costorderTotal);

			$this->display('wxpay');
		}else{
			exit;
		}	
	}

	//支付宝账单缴费
	public function alipay(){
		//获取参数
		$orderid = I('get.oid', 0);
		$roomnumber = I('get.rn', '');
		$type = I('get.type', 0); //入口类型
		
		//获取合并后的订单
		$orderInfo = M('order')->where(array(
			'id' => $orderid,
			'status' => 0,
			'room_number' => $roomnumber
		))->find();
		
		if(count($orderInfo)){
			if(!$type){ //直接调起支付宝
				$array = array(
					"out_trade_no" => $orderInfo['order_sn'],
					"total_amount" => $orderInfo['point'],
					"product_code" => 'QUICK_WAP_WAY',
					"subject"      => $orderInfo['desc'],
					"body"         => $orderInfo['desc']
				);
				
				$result = D('Alipay')->createWapAction($array);
			}else{ //跳转到其他界面
				$this->assign('orderinfo', $orderInfo);
				$this->display('WapCost/alipay');
			}
		}
	}
	
	//微信充值支付
	public function wxpay(){
		$point = I('point') ? (int)I('point') : 0;
		$userid = I('uid') ? (int)I('uid') : 0; //登陆用户
		
		import("Org.Util.JsApiPay");
		$jsApi = new \JsApiPay();
		$openid = $jsApi->GetOpenid();
		//获取金额
		$ordersn = 'MMGY_'. time();
		if(empty($point)){
			exit;
		}
		//根据用户ID获取用户信息
		$userinfo = D('Member')->getMemberInfoById($userid);
		if(is_array($userinfo) && count($userinfo)){
			//添加支付日志
			$row = D('Gobacklog')->addGobacklogInfo(array(
				'typeid' => 5,
				'pay_type' => 2,
				'contract' => $userinfo['contract'],
				'userid' => $userinfo['member_id'],
				'nickname' => $userinfo['member_nick'],
				'roomnumber' => $userinfo['room_number'],
				'acount' => sprintf('%.2f', $point),
				'other' => sprintf('%.2f', $point),
				'weixin' => sprintf('%.2f', $point),
				'admin_nick' => '自主充值'
			));
			
			if($row){
				//设置支付参数
				$input = new \WxPayUnifiedOrder();
				$input->SetBody("会员充值");
				$input->SetOut_trade_no($ordersn);
				$input->SetTotal_fee($point * 100);
				$input->SetTime_start(date("YmdHis"));
				$input->SetTime_expire(date("YmdHis", time() + 600));
				$input->SetNotify_url("http://mamagy.com/xj/wap/wxnotify.html"); //回调函数
				$input->SetTrade_type("JSAPI");
				$input->SetOpenid($openid);
				//统一订单
				$order = \WxPayApi::unifiedOrder($input);
				//获取JS参数
				$param = $jsApi->GetJsApiParameters($order);
				//getPrepayId
				$this->assign('jsApiParameters', $param);
				$this->assign('total_fee', $point);
			}
			
			$this->display();
		}
	}
	
	/**
	 * 微信支付回调
	 **/
	public function wxnotify(){
		$string = file_get_contents("php://input");
		$file_get_contents = (array)simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
		$result_code = $file_get_contents['result_code'];
		if($result_code == 'SUCCESS' && $file_get_contents['return_code'] == 'SUCCESS'){
			$out_trade_no = $file_get_contents['out_trade_no'];
			//获取订单详情
			$orderInfo = D('Paylog')->getOrderInfoByOrderSn($out_trade_no);
			if($orderInfo['status'] == 0){
				//修改订单状态
				$row = D('Paylog')->editOrderInfoByOrderSn($out_trade_no, 1, 2);
				//修改账单状态
				$row = D('Costlog')->editCostLogInfo(array(
					'order_id' => array('in', $orderInfo['costorder'])
				), array(
					'status' => 1
				));
				//获取用户数据
				$userinfo = D('Member')->getMemberInfoByContractArray($orderInfo['contract']);
				//查询账单数据
				$costorder = D('Costlog')->getCostLogInfo(array(
					'order_id' => array('in', $orderInfo['costorder'])
				));
				$rent = $property = $water = $electric = 0;
				if(count($costorder)) foreach($costorder as $or){
					$rent += $or['rent'];
					$property += $or['property'];
					$water += $or['rates1']; //( + $or['rates2'] + $or['rates3']);
					$electric += $or['rates2'];
					//修改时间
					if($or['rent'] > 0){
						D('Member')->editMemberRentTimeAndPtime(array(
							'member_id' => $userinfo['member_id'],
							'leaving_time' => array('elt', $or['end_time'])
						), array(
							'checkin_time' => $or['begin_time'],
							'leaving_time' => $or['end_time']
						));
					}
					//修改物业有效时间
					if($or['property'] > 0){
						D('Member')->editMemberRentTimeAndPtime(array(
							'member_id' => $userinfo['member_id'],
							'property_time' => array('elt', $or['end_time'])
						), array(
							'property_time' => $or['end_time']
						));
					}
				}
				//新增GoBackLog数据
				if(is_array($userinfo) && count($userinfo)){
					$go_data = array(
						'typeid' => 1,
						'contract' => $userinfo['contract'],
						'userid' => $userinfo['member_id'],
						'nickname' => $userinfo['member_nick'],
						'roomnumber' => $userinfo['room_number'],
						'rent' => $rent,
						'property' => $property,
						'water_power' => $water,
						'electric' => $electric,
						'acount' => $file_get_contents['total_fee']/100,
						'pay_type' => 2,
						'pay_card' => $file_get_contents['openid'],
						'createtime' => time(),
						'remark' => $orderInfo['desc'],
						'status' => 1,
						'weixin' => $file_get_contents['total_fee']/100,
						'weixin_ordersn' => $file_get_contents['transaction_id']
					);
					
					$row = D('Gobacklog')->addGobacklogInfo($go_data);
				}
				
				$data = array('return_code' => '<![CDATA[SUCCESS]]>', 'return_msg' => '<![CDATA[OK]]>');
			}
		}else{
			$data = array('return_code' => '<![CDATA[FAIL]]>', 'return_msg' => '<![CDATA[OK]]>');
		}
		
		$this->response($data, 'json');
	}
	
	/**
	 * 支付宝回调
	 **/
	public function alinotify(){
		$string = file_get_contents("php://input");
		$discount = I('post.discount'); //折扣价
		$trade_no = I('post.trade_no'); //支付宝交易号
		$buyer_id = I('post.buyer_id'); //买家ID
		$buyer_email = I('post.buyer_email'); //买家支付账号
		$out_trade_no = I('post.out_trade_no'); //订单号
		$seller_id = I('post.seller_id'); //卖家账号ID
		$seller_email = I('post.seller_email'); //卖家账号
		$total_fee = I('post.invoice_amount'); //支付金额
		$gmt_payment = urldecode(I('gmt_payment')); //支付时间
		$trade_status = I('post.trade_status'); //订单状态 TRADE_SUCCESS 支付成功 WAIT_BUYER_PAY 创建订单成功 TRADE_FINISHED 订单结束
		$notify_id = I('post.notify_id'); //通知校验ID
		
		if(D('Alipay')->checkAlipayNotifyId($notify_id)){
			//获取订单详情
			$orderInfo = D('Paylog')->getOrderInfoByOrderSn($out_trade_no);
			if($orderInfo['status'] == 0){
				//修改订单状态
				$row = D('Paylog')->editOrderInfoByOrderSn($out_trade_no, 1, 2);
				//修改账单状态
				$row = D('Costlog')->editCostLogInfo(array(
					'order_id' => array('in', $orderInfo['costorder'])
				), array(
					'status' => 1
				));
				//获取用户数据
				$userinfo = D('Member')->getMemberInfoByContractArray($orderInfo['contract']);
				//查询账单数据
				$costorder = D('Costlog')->getCostLogInfo(array(
					'order_id' => array('in', $orderInfo['costorder'])
				));
				$rent = $property = $water = $electric = 0;
				if(count($costorder)) foreach($costorder as $or){
					$rent += $or['rent'];
					$property += $or['property'];
					$water += $or['rates1']; //( + $or['rates2'] + $or['rates3']);
					$electric += $or['rates2'];
					//修改时间
					if($or['rent'] > 0){
						D('Member')->editMemberRentTimeAndPtime(array(
							'member_id' => $userinfo['member_id'],
							'leaving_time' => array('elt', $or['end_time'])
						), array(
							'checkin_time' => $or['begin_time'],
							'leaving_time' => $or['end_time']
						));
					}
					//修改物业有效时间
					if($or['property'] > 0){
						D('Member')->editMemberRentTimeAndPtime(array(
							'member_id' => $userinfo['member_id'],
							'property_time' => array('elt', $or['end_time'])
						), array(
							'property_time' => $or['end_time']
						));
					}
				}
				//新增GoBackLog数据
				if(is_array($userinfo) && count($userinfo)){
					$go_data = array(
						'typeid' => 1,
						'contract' => $userinfo['contract'],
						'userid' => $userinfo['member_id'],
						'nickname' => $userinfo['member_nick'],
						'roomnumber' => $userinfo['room_number'],
						'rent' => $rent,
						'property' => $property,
						'water_power' => $water,
						'electric' => $electric,
						'acount' => $total_fee,
						'pay_type' => 2,
						'pay_card' => $buyer_email,
						'createtime' => time(),
						'remark' => $orderInfo['desc'],
						'status' => 1,
						'alipay' => $total_fee,
						'alipay_ordersn' => $trade_no
					);
					
					$row = D('Gobacklog')->addGobacklogInfo($go_data);
				}
				
				echo 1;
			}
		}else{
			echo 0;
		}
	}
	
	/**
	 * HD pay log
	 **/
	public function hdpay(){
		if(IS_GET){
			//查询信息
			$info = D('Member')->getMemberInfoByPhone($phone, $code);
			//查询费用
			$this->display('index3');
		}else{
			
		}
	}
	
	//判断是否存在卡
	public function checkCard(){
		$cardno = I('card') ? trim(I('card')) : '';
		$room_number = I('room_number') ? trim(I('room_number')) : '';
		
		$info = D('Card')->getRoomCardInfoByCardUid($cardno);
		if(is_array($info) && count($info)){
			$infos = D('Roomcard')->getRoomCardInfoByWhere(array(
				'card_udid' => $cardno,
				//'room_number' => $room_number,
				'is_back' => 0
			));
			
			if(is_array($infos) && count($infos) && $infos['room_number'] != $room_number){
				echo 2;
			}else{
				echo 1;
			}
		}else{
			echo 0;
		}
	}
	
	/**
	 * 制卡需要
	 **/
	public function card(){
		$data['card'] = I('get.card') ? trim(I('get.card')) : '';
		$data['card_udid'] = $data['card'];
		$data['lock_id'] = I('get.lock_id') ? trim(I('get.lock_id')) : '';
		$data['member_id'] = I('get.uid') ? (int)I('get.uid') : 0;
		$data['card_type'] = I('get.iscq') ? (int)I('get.iscq') : 6;
		$data['createtime'] = time();
		//获取用户详情
		$userinfo = D('Member')->getMemberInfoById($data['member_id']);
		//判断是否存在用户信息
		if(is_array($userinfo) && count($userinfo)){
			if($userinfo['leaving_time'] < time()){
				//判断是否在48小时之内，并且是长租客人 istype == 1
				if($userinfo['istype'] == 1 && $this->diffBetweenTwoDays($userinfo['leaving_time'], time()) <= 2){
					//设置参数
					$data['checkin_time'] = time();
					//判断是否存在制卡记录
					$infos = D('Roomcard')->getRoomCardInfoByWhere(array(
						'card_udid' => $data['card_udid'],
						'member_id' => $data['member_id'],
						'is_back' => 0
					));
					
					if(is_array($infos) && count($infos)){
						if(D('Roomcard')->editRoomCardInfoByLogIds(array('createtime' => time()), $infos['id']) !== false){
							$this->ajaxReturn(array(
								'errCode' => 1,
								'errMsg' => 'Success.',
							));
						}else{
							$this->ajaxReturn(array(
								'errCode' => 0,
								'errMsg' => 'Fail!',
							));
						}
					}else{
						$data['leav_time'] = time() + 86400; //延长一天
						$data['room_number'] = $userinfo['room_number'];
						$data['m_nickname'] = $userinfo['member_nick'];
						
						$row = D('Roomcard')->addRoomCardnfo($data);
						if($row){
							$this->ajaxReturn(array(
								'errCode' => 1,
								'errMsg' => 'Success.',
							));
						}
					}
				}
			}else{
				//设置参数
				if($userinfo['checkin_time'] >= time()){
					$data['checkin_time'] = $userinfo['checkin_time'];
				}else{
					$data['checkin_time'] = time();
				}
				//判断是否存在制卡记录
				$infos = D('Roomcard')->getRoomCardInfoByWhere(array(
					'card_udid' => $data['card_udid'],
					'member_id' => $data['member_id'],
					'is_back' => 0
				));
				
				if(is_array($infos) && count($infos)){
					if(D('Roomcard')->editRoomCardInfoByLogIds(array('createtime' => time()), $infos['id']) !== false){
						$this->ajaxReturn(array(
							'errCode' => 1,
							'errMsg' => 'Success.',
						));
					}else{
						$this->ajaxReturn(array(
							'errCode' => 0,
							'errMsg' => 'Fail!',
						));
					}
				}else{
					//判断结束时间是否是大于1个月
					$month = $this->getMonthNum(date('Y-m-d', $userinfo['leaving_time']), date('Y-m-d', time()));
					if($month > 1){
						$data['leav_time'] = strtotime("+1 month");
					}else{
						$data['leav_time'] = $userinfo['leaving_time'];
					}
				}
				$data['room_number'] = $userinfo['room_number'];
				$data['m_nickname'] = $userinfo['member_nick'];
				
				$row = D('Roomcard')->addRoomCardnfo($data);
				if($row){
					$this->ajaxReturn(array(
						'errCode' => 1,
						'errMsg' => 'Success.',
					));
				}
			}
		}else{
			$this->ajaxReturn(array(
				'errCode' => 0,
				'errMsg' => 'Fail!',
			));
		}
	}

	private function getMonthNum( $date1, $date2, $tags='-' ){
	 	$date1 = explode($tags,$date1);
	 	$date2 = explode($tags,$date2);
	 	return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);
	}

	private function diffBetweenTwoDays ($second1, $second2){
  		if ($second1 < $second2) {
   			$tmp = $second2;
    		$second2 = $second1;
    		$second1 = $tmp;
  		}

  		return ($second1 - $second2) / 86400;
	}
}

